package com.wxzz.elearing.livetelecast.amqp.consume;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import com.wxzz.elearing.livetelecast.amqp.producer.LiveMessageProducer;
import com.wxzz.elearing.livetelecast.amqp.producer.PlatformLivetelecastProducer;
import com.wxzz.elearing.livetelecast.entity.Activity;
import com.wxzz.elearing.livetelecast.entity.PlatformLivetelecast;
import com.wxzz.elearing.livetelecast.entity.WxUserPlatformLivetelecast;
import com.wxzz.elearing.livetelecast.mapper.ActivityMapper;
import com.wxzz.elearing.livetelecast.mapper.PlatformLivetelecastMapper;
import com.wxzz.elearing.livetelecast.mapper.WxUserPlatformLivetelecastMapper;
import com.wxzz.elearing.livetelecast.service.IWxUserPlatformLivetelecastService;
import com.wxzz.elearning.common.bean.RabbitMQConfiguration;
import com.wxzz.elearning.common.bean.SmsConfig;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class PlatformLivetelecastListener {

    private static final Logger logger = LoggerFactory.getLogger(PlatformLivetelecastListener.class);

    @Autowired
    private PlatformLivetelecastMapper platformLivetelecastMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queues = RabbitMQConfiguration.WXZZ_DELAY_QUEUE)
    public void onDelayMessage(@Payload String msg,
                               @Headers Map<String, Object> headers,
                               Channel channel, Message message) throws IOException {
        logger.info("监听延时交换机, 收到消息: {}", message);
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            this.process(msg); // 内部处理
        } catch (Exception e) {
            boolean redelivered = (boolean) headers.get(AmqpHeaders.REDELIVERED);
            channel.basicNack(deliveryTag, false, !redelivered);
        }
    }

    @Autowired
    private WxUserPlatformLivetelecastMapper wxUserPlatformLivetelecastMapper;

    @Autowired
    private ActivityMapper activityMapper;

    private void process(String msg) {
        // log.info("livetelecastQueue 接收时间:{} 接收内容:{}", LocalDateTime.now().toString(), msg);
        JSONObject map = JSON.parseObject(msg);
        //消息唯一标识
        String uuid = redisTemplate.opsForValue().get(RedisConstants.DEAL_QUEUE_LIVETELECAST + map.get("id") + map.get("type") + map.get("status"));
        //验证
        if (map.get("uuid").equals(uuid)) {
            if (RabbitMQConfiguration.QUEUE_TYPE1.equals(map.get("type"))) {
                // 直播间状态更新
                PlatformLivetelecast platformLivetelecast = platformLivetelecastMapper.selectById(map.getLong("id"));
                if (platformLivetelecast != null) {
                    platformLivetelecast.setLivetelecastStatus(1);
                    platformLivetelecastMapper.updateById(platformLivetelecast);
                    logger.info("服务消费-id为:{}的直播间状态修改成功，修改为开播", map.get("id"));
                } else {
                    logger.error("服务消费-id为:{}的直播间状态修改错误，原因 id数据查询不存在", map.get("id"));
                }
            } else if (RabbitMQConfiguration.QUEUE_TYPE2.equals(map.get("type"))) {
                // 直播推流状态更新
                PlatformLivetelecast platformLivetelecast = platformLivetelecastMapper.selectById(map.getLong("id"));
                if (platformLivetelecast != null) {
                    platformLivetelecast.setPushStatus(map.getInteger("status"));
                    platformLivetelecastMapper.updateById(platformLivetelecast);
                    logger.info("服务消费-id为:{}的直播推流状态修改成功，修改为：{}", map.get("id"), map.get("status"));
                } else {
                    logger.error("服务消费-id为:{}的直播推流状态修改错误，原因 id查询不存在不存在", map.get("id"));
                }
            } else if (RabbitMQConfiguration.QUEUE_TYPE3.equals(map.get("type"))) {
                // 直播开播提醒
                PlatformLivetelecast platformLivetelecast = platformLivetelecastMapper.selectById(map.getLong("id"));
                if (platformLivetelecast != null) {
                    List<WxUserPlatformLivetelecast> wxUserPlatformLivetelecasts = wxUserPlatformLivetelecastMapper.selectList(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                            .eq(WxUserPlatformLivetelecast::getPayStatus, 1)
                            .eq(WxUserPlatformLivetelecast::getType, 0)
                            .eq(WxUserPlatformLivetelecast::getPlatformLivetelecastId, platformLivetelecast.getId()));
                    List<String> phones = new ArrayList<>();
                    List<Long> wxUserIds = new ArrayList<>();
                    for (WxUserPlatformLivetelecast wxUserPlatformLivetelecast : wxUserPlatformLivetelecasts) {
                        phones.add(wxUserPlatformLivetelecast.getPhone());
                        wxUserIds.add(wxUserPlatformLivetelecast.getWxUserId());
                    }
                    //发送消息
                    SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                    systemMessageMqDto.setPhones(phones);
                    systemMessageMqDto.setTemplateId(SmsConfig.liveWillStartId);
                    systemMessageMqDto.setParams(new ArrayList<String>() {
                        {
                            add(platformLivetelecast.getLivetelecastName());
                            add(platformLivetelecast.getStartTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        }
                    });
                    systemMessageMqDto.setMessageDetail("您预约的" + platformLivetelecast.getLivetelecastName() + "直播于" + platformLivetelecast.getStartTime() + "时开播,请您及时收看");
                    systemMessageMqDto.setMessageTitle("直播-开播提醒");
                    systemMessageMqDto.setWxUserIds(wxUserIds);
                    liveMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
                } else {
                    logger.error("服务消费-id为:{}的直播推流状态修改错误，原因 id查询不存在不存在", map.get("id"));
                }
            } else if (RabbitMQConfiguration.QUEUE_TYPE6.equals(map.get("type"))) {
                // 活动开始
                Activity activity = activityMapper.selectById(map.getLong("id"));
                if (activity != null) {
                    activity.setActivityStatus(map.getInteger("status"));
                    activityMapper.updateById(activity);
                    //发送结束时间消息
                    //platformLivetelecastProducer.updateActivityEndStatus(activity.getId(),activity.getActivityEndTime());
                } else {
                    logger.error("服务消费-id为:{}的活动修改错误，原因 id查询不存在不存在", map.get("id"));
                }
            } else if (RabbitMQConfiguration.QUEUE_TYPE7.equals(map.get("type"))) {
                // 活动结束
                Activity activity = activityMapper.selectById(map.getLong("id"));
                if (activity != null) {
                    activity.setActivityStatus(map.getInteger("status"));
                    activityMapper.updateById(activity);
                } else {
                    logger.error("服务消费-id为:{}的活动状态修改错误，原因 id查询不存在不存在", map.get("id"));
                }
            } else if (RabbitMQConfiguration.QUEUE_TYPE9.equals(map.get("type"))) {
                // 活动开始提醒
                Activity activity = activityMapper.selectById(map.getLong("id"));
                if (activity != null) {
                    List<WxUserPlatformLivetelecast> wxUserPlatformLivetelecasts = wxUserPlatformLivetelecastMapper.selectList(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                            .eq(WxUserPlatformLivetelecast::getPayStatus, 1)
                            .eq(WxUserPlatformLivetelecast::getType, 1)
                            .eq(WxUserPlatformLivetelecast::getActivityId, activity.getId()));
                    List<String> phones = new ArrayList<>();
                    List<Long> wxUserIds = new ArrayList<>();
                    for (WxUserPlatformLivetelecast wxUserPlatformLivetelecast : wxUserPlatformLivetelecasts) {
                        phones.add(wxUserPlatformLivetelecast.getPhone());
                        wxUserIds.add(wxUserPlatformLivetelecast.getWxUserId());
                    }
                    //发送消息
                    SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                    systemMessageMqDto.setPhones(phones);
                    systemMessageMqDto.setTemplateId(SmsConfig.activityWillStartId);
                    systemMessageMqDto.setParams(new ArrayList<String>() {
                        {
                            add(activity.getActivityName());
                            add(activity.getActivityStartTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        }
                    });
                    systemMessageMqDto.setMessageDetail("您预约的" + activity.getActivityName() + "活动于" + activity.getActivityStartTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")) + "时开始,请您及时参与");
                    systemMessageMqDto.setMessageTitle("活动-开始提醒");
                    systemMessageMqDto.setWxUserIds(wxUserIds);
                    liveMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
                } else {
                    logger.error("服务消费-id为:{}的直播推流状态修改错误，原因 id查询不存在不存在", map.get("id"));
                }
            } else {
                logger.error("服务消费-id为:{}的消费类型不存在：{}", map.get("id"), map.get("type"));
            }
        } else {
            logger.error("服务消费-失败：uuid不匹配：{}，{}", uuid, map.get("uuid"));
        }
    }

    @Autowired
    private PlatformLivetelecastProducer platformLivetelecastProducer;

    @Autowired
    private LiveMessageProducer liveMessageProducer;

}
